package edu.yuhf.service;

import java.util.List;
import java.util.Optional;

import edu.yuhf.dao.iface.RoleDao;
import edu.yuhf.dao.mysql.RoleJdbcDaoImpl;
import edu.yuhf.domain.Page;
import edu.yuhf.domain.Role;
import edu.yuhf.service.iface.RoleService;

public class RoleServiceImpl implements RoleService {
	
	private RoleDao roleDao=new RoleJdbcDaoImpl();

	@Override
	public void getRoles(Page<List<Role>> page) {
		 roleDao.queryRoles(page);
		 int totalRowNumber=roleDao.queryTotalRowNumber(page);
		 int totalPageNumber=0==totalRowNumber%page.getPageNumber()?totalRowNumber/page.getPageNumber():totalRowNumber/page.getPageNumber()+1;
		 page.setTotalRowNumber(totalRowNumber);
		 page.setTotalPageNumber(totalPageNumber);
	}

	@Override
	public boolean addRole(Role role) {
		boolean flag=false;
		if(1==roleDao.insertRole(role)) {
			flag=true;
		}
		return flag;
	}

	@Override
	public boolean removeRole(String ids) {
		boolean flag=false;
		if(roleDao.deleteRoles(ids)!=0) {
			flag=true;
		}
		return flag;
	}

	@Override
	public Optional<Role> getRoleById(int id) {
		return Optional.ofNullable(roleDao.queryRoleById(id));
	}

	@Override
	public boolean setRole(Role role) {
		boolean flag=false;
		if(roleDao.updateRole(role)==1) {
			flag=true;
		}
		return flag;
	}

	@Override
	public List<Role> getRolesByUserId(int userId) {
		List<Role> list=roleDao.queryRoles();
		List<Role> checkedList=roleDao.queryRolesByUserId(userId);
		list.forEach(role->{
			checkedList.forEach(checkedRole->{
				if(role.getId()==checkedRole.getId()) {
					role.setChecked(true);
				}
			});
		});
		return list;
	}

}
